﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.IO;

namespace Microsoft.Wim.Tests
{
    [TestClass]
    public class RemountImageTests : TestBase
    {
        [TestMethod]
        public void RemountImageTest()
        {
            using (var imageHandle = WimgApi.LoadImage(TestWimHandle, 1))
            {
                WimgApi.MountImage(imageHandle, MountPath, WimMountImageOptions.Fast | WimMountImageOptions.DisableDirectoryAcl | WimMountImageOptions.DisableFileAcl | WimMountImageOptions.DisableRPFix | WimMountImageOptions.ReadOnly);

                try
                {
                    VerifyMountState(imageHandle, WimMountPointState.Mounted);

                    KillWimServ();

                    VerifyMountState(imageHandle, WimMountPointState.Remountable);

                    WimgApi.RemountImage(MountPath);

                    VerifyMountState(imageHandle, WimMountPointState.Mounted);
                }
                finally
                {
                    WimgApi.UnmountImage(imageHandle);
                }
            }
        }

        [TestMethod]
        public void RemountImageTest_ThrowsArgumentNullException_mountPath()
        {
            AssertThrows<ArgumentNullException>("mountPath", () =>
                WimgApi.RemountImage(null));
        }

        [TestMethod]
        public void RemountImageTest_ThrowsDirectoryNotFoundException_mountPath()
        {
            AssertThrows<DirectoryNotFoundException>(() =>
                WimgApi.RemountImage(Path.Combine(TestContext.DeploymentDirectory, Guid.NewGuid().ToString())));
        }

        private void KillWimServ()
        {
            var wimServProcesses = Process.GetProcessesByName("wimserv");

            Assert.AreNotEqual(0, wimServProcesses.Length, "WimServ.exe processes were found");

            foreach (var process in wimServProcesses)
            {
                process.Kill();
            }
        }

        private void VerifyMountState(WimHandle imageHandle, WimMountPointState expectedMountPointState)
        {
            var mountedImageInfo = WimgApi.GetMountedImageInfoFromHandle(imageHandle);

            Assert.AreEqual(expectedMountPointState, mountedImageInfo.State | expectedMountPointState);
        }
    }
}